package com.attendance.www.hr.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.dao.mapper.HolidayMapper;
import com.attendance.www.hr.dao.mapper.SchedulDayMapper;
import com.attendance.www.hr.entitys.Holiday;
import com.attendance.www.hr.entitys.HolidayExample;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IHolidayExcelService;
import com.attendance.www.hr.service.ISchedulWeekService;

@Service
public class HolidayExcelServiceImpl implements IHolidayExcelService {

	@Resource
	private HolidayMapper holidayDao;
	@Resource
	private SchedulDayMapper schedulDayDao;
	@Resource
	private ISchedulWeekService schedulWeekService; 

	private Map<Date, Integer> addHolidayMap;
	
	private Map<Date, Holiday> holidayMap;

	@Override
	public List<String> importHoliday(Workbook work, String type) {
		Calendar calendar = Calendar.getInstance();
		int yearCar= calendar.get(Calendar.YEAR);
		
		List<Integer> yearIntList=new ArrayList<Integer>();
		yearIntList.add(yearCar);
		yearIntList.add(yearCar+1);
		
		HolidayExample holidayExample=new HolidayExample();
		holidayExample.createCriteria().andHolidayYearIn(yearIntList);
		List<Holiday> holidayList=holidayDao.selectByExample(holidayExample);
		
		addHolidayMap = new HashMap<Date, Integer>();
		holidayMap = new HashMap<Date, Holiday>();
		List<String> successList = new ArrayList<String>();
	
		// 获取工作表的数量	
		int sheetNum = work.getNumberOfSheets();
		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("节假日")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					Holiday holiday = new Holiday();// 创建岗位对象
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						continue;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						continue;
					}

					// 判断第一列节假日名称的合法性
					if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
						holiday.setHolidayName(row.getCell(0).toString());
					} else {
						str.append("节假日名称不能为空,");
					}

					// 判断第二列节假日年份的合法性
					if (row.getCell(1) != null && StringUtils.isNotBlank(row.getCell(1).toString())) {
						holiday.setHolidayYear(Double.valueOf(row.getCell(1).toString()).intValue());
					} else {
						str.append("节假日年份不能为空,");
					}

					// 判断第三列节假日日期的合法性
					// 第四列(开始时间)
					if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
						Date fromDate = new Date();
						try {
							fromDate = row.getCell(2).getDateCellValue();
						} catch (Exception e) {
						}
						holiday.setHolidayDate(fromDate);
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
						SimpleDateFormat formatters = new SimpleDateFormat("yyyy-MM-dd");
						String year = formatter.format(fromDate);
						String dateString = formatters.format(fromDate);
						if (!year.equals(String.valueOf(holiday.getHolidayYear()))) {
							str.append("年份与日期不符合,");
						}
						if (!type.equals("1")) {
							if (addHolidayMap.containsKey(fromDate)) {
								if (addHolidayMap.get(fromDate).intValue() > 0) {
									str.insert(0, "第" + addHolidayMap.get(fromDate) + "行和");
									str.append("假期日期为(" + dateString + ")重复,");
								} else {
									str.append("假期日期为(" + dateString + ")已存在,");
								}
							}
						}
					} else {
						str.append("节假日日期不能为空,");
					}

					// 判断第二列节假日是否上班的合法性
					if (row.getCell(3) != null && StringUtils.isNotBlank(row.getCell(3).toString())) {
						if (row.getCell(3).toString().equals("班")) {
							holiday.setIsToWork(1);
						} else if (row.getCell(3).toString().equals("休")) {
							holiday.setIsToWork(0);
						} else {
							str.append("状态填写不正确");
						}

					} else {
						str.append("上班状态不能为空");
					}
					
					// 判断第五列法定假日状态的合法性
					if (row.getCell(3).toString().equals("休")) {
						if (row.getCell(4) != null && StringUtils.isNotBlank(row.getCell(4).toString())) {
							if (row.getCell(4).toString().equals("是")) {
								holiday.setIsLegal(1);
							} else if (row.getCell(4).toString().equals("否")) {
								holiday.setIsLegal(0);
							} else {
								str.append("法定节假日状态不正确,");
							}
						} else {
							str.append("法定节假日状态未填写,");
						}
					} else if (row.getCell(3).toString().equals("班")) {
						if (row.getCell(4).toString() != null && StringUtils.isNotBlank(row.getCell(4).toString())) {
							if (row.getCell(4).toString().equals("否")) {
								holiday.setIsLegal(0);
							} else if (row.getCell(4).toString().equals("是")) {
								str.append("上班状态下，法定节假日状态默认为否");
							} else {
								str.append("法定节假日状态格式不正确,");
							}
						}
					}
					
					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						try {
							//添加数据前，验证是否存在，不存在添加数据库中
							Integer holidayId=null;
							boolean types=true;
							for(int ih=0;ih<holidayList.size();ih++) {
								if(holidayList.get(ih).getHolidayDate().getTime()==holiday.getHolidayDate().getTime()) {
									holidayId=holidayList.get(ih).getHolidayId();
									types=false;
									break;
								}
							}
							if(types) {
								// 添加
								holidayDao.insertSelective(holiday);
							}else {
								holiday.setHolidayId(holidayId);
								holidayDao.updateByPrimaryKeySelective(holiday);
							}
						} catch (Exception e) {
							throw new ResultFaultException("7_00005");
						}
						holidayMap.put(holiday.getHolidayDate(), holiday);
						addHolidayMap.put(holiday.getHolidayDate(), i + 1);
					} else {
						String errorStr = str.toString().substring(0, str.toString().length());
						errorMsgList.add(errorStr);
					}
				}
				
				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("7_00005", errorMsgList);
				}
				if (successList.size() > 0) {
					successList.add(0, "节假日导入完成,并覆盖数据如下：");
				} else {
					successList.add(0, "节假日导入完成");
					//处理法定节假日，先后日期问题
					schedulWeekService.saveSchedulDayKeyAuto();
				}
				return successList;
			}
		}
		throw new ResultFaultException("7_000015");
	}
}
